﻿using System.Data;

namespace Daemon.Data.Substructure.Framework.Extension
{
	public static class DataTableExtension
	{
		/// <summary>
		/// Join two different struct data tables as one. Extension the data table at the column level.
		/// </summary>
		/// <param name="dt1"></param>
		/// <param name="dt2"></param>
		/// <returns></returns>
		public static DataTable UniteTable(this DataTable dt1, DataTable dt2)
		{
			DataTable dt3 = dt1.Clone();
			for (int i = 0; i < dt2.Columns.Count; i++)
			{
				dt3.Columns.Add(dt2.Columns[i].ColumnName);
			}

			object[] obj = new object[dt3.Columns.Count];

			for (int i = 0; i < dt1.Rows.Count; i++)
			{
				dt1.Rows[i].ItemArray.CopyTo(obj, 0);
				dt3.Rows.Add(obj);
			}

			if (dt1.Rows.Count >= dt2.Rows.Count)
			{
				HandleNonNewRowType(dt1, dt2, dt3);
			}
			else
			{
				HandleAddNewRowType(dt1, dt2, dt3);
			}

			return dt3;
		}

		private static void HandleAddNewRowType(DataTable dt1, DataTable dt2, DataTable dt3)
		{
			DataRow dr3;
			for (int i = 0; i < dt2.Rows.Count - dt1.Rows.Count; i++)
			{
				dr3 = dt3.NewRow();
				dt3.Rows.Add(dr3);
			}

			for (int i = 0; i < dt2.Rows.Count; i++)
			{
				for (int j = 0; j < dt2.Columns.Count; j++)
				{
					dt3.Rows[i][j + dt1.Columns.Count] = dt2.Rows[i][j].ToString();
				}
			}
		}

		private static void HandleNonNewRowType(DataTable dt1, DataTable dt2, DataTable dt3)
		{
			for (int i = 0; i < dt2.Rows.Count; i++)
			{
				for (int j = 0; j < dt2.Columns.Count; j++)
				{
					dt3.Rows[i][j + dt1.Columns.Count] = dt2.Rows[i][j].ToString();
				}
			}
		}
	}
}
